<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-card class="search-card">
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子..."
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch">
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="handleSearch">
        </el-button>
      </el-input>

      <div class="filter-options">
        <el-radio-group v-model="filter.sort" @change="fetchPosts">
          <el-radio-button label="newest">最新</el-radio-button>
          <el-radio-button label="hottest">最热</el-radio-button>
        </el-radio-group>

        <div class="right-options">
          <el-button
            icon="el-icon-refresh"
            @click="fetchPosts"
            :loading="loading"
            size="small"
            title="刷新列表"
            style="margin-right: 10px;">
            刷新
          </el-button>

          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleCreatePost">
            发帖
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="post-list">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="posts.length === 0" class="empty-tip">
        <el-empty description="暂无帖子"></el-empty>
      </div>

      <div v-else>
        <!-- 直接使用内联的 PostItem 模板 -->
        <div
          v-for="post in posts"
          :key="post.id"
          class="post-item"
        >
          <h2 class="post-title">{{ post.title }}</h2>
          <p class="post-content">{{ post.content }}</p>
          <div class="post-actions">
            <el-tooltip :content="post.isLiked ? '取消点赞' : '点赞'" placement="top">
              <el-button
                type="text"
                :class="['action-btn', {'active': post.isLiked}]"
                @click="handleLike(post.id)"
              >
                <i :class="post.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                <span>{{ post.likeCount || '0' }}</span>
              </el-button>
            </el-tooltip>
            
            <el-tooltip :content="post.isFavorited ? '取消收藏' : '收藏'" placement="top">
              <el-button
                type="text"
                :class="['action-btn', {'active': post.isFavorited}]"
                @click="handleFavorite(post.id)"
              >
                <i :class="post.isFavorited ? 'el-icon-collection' : 'el-icon-collection-tag'"></i>
                <span>{{ post.favoriteCount || '0' }}</span>
              </el-button>
            </el-tooltip>
            
            <el-button
              type="text"
              class="action-btn"
              @click="handleComment(post.id)"
            >
              <i class="el-icon-chat-line-round"></i>
              <span>{{ post.commentCount || '0' }}</span>
            </el-button>
          </div>
        </div>

        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 发帖对话框 -->
    <el-dialog
      title="发布新帖"
      :visible.sync="dialogVisible"
      width="70%">
      <el-form :model="postForm" :rules="postRules" ref="postForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="postForm.content"
            :rows="10"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="标签">
          <el-tag
            v-for="tag in postForm.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(tag)">
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputTagVisible"
            v-model="inputTagValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPost">发 布</el-button>
      </span>
    </el-dialog>

    <!-- AI 寻宠浮窗按钮 -->
    <el-button
      type="primary"
      icon="el-icon-search"
      class="ai-pet-finder-btn"
      @click="showAIPetFinder = true">
      AI 寻宠
    </el-button>

    <!-- AI 寻宠浮窗 -->
    <el-dialog
      title="AI 寻宠"
      :visible.sync="showAIPetFinder"
      width="50%">
      <el-form :model="petFinderForm" ref="petFinderForm">
        <el-form-item label="上传宠物图片">
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="beforePetImageUpload">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <img v-if="petImageUrl" :src="petImageUrl" alt="宠物图片" style="max-width: 100%; margin-top: 10px;">
        </el-form-item>

        <el-form-item label="宠物特征描述">
          <el-input
            type="textarea"
            v-model="petFinderForm.description"
            :rows="5"
            placeholder="请描述宠物的特征"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAIPetFinder = false">取消</el-button>
        <el-button type="primary" @click="submitPetFinder">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import { mapGetters, mapState } from 'vuex'

export default {
  name: 'Community',
  data() {
    return {
      searchQuery: '',
      loading: false,
      posts: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      filter: {
        sort: 'newest'
      },
      dialogVisible: false,
      postForm: {
        title: '',
        content: '',
        tags: []
      },
      postRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      inputTagVisible: false,
      inputTagValue: '',
      showAIPetFinder: false,
      petFinderForm: {
        description: ''
      },
      petImageUrl: '',
      username: localStorage.getItem('username') || '' // 从localStorage获取用户名
    }
  },
  computed: {
    ...mapState({
      userId: state => state.user.id,
      userName: state => state.user.name
    })
  },
  created() {
    // 添加调试日志
    console.log('用户信息:', {
      userId: this.userId,
      userName: this.userName,
      localUsername: this.username,
      token: getToken()
    });
    
    this.fetchPosts()
  },
  methods: {
    // 获取帖子列表
    fetchPosts() {
      this.loading = true
      
      // 直接使用 userId
      console.log('使用的用户ID:', this.userId);
      
      request({
        url: '/api/community/posts',
        method: 'get',
        params: {
          page: this.currentPage - 1,
          size: this.pageSize,
          sort: this.filter.sort,
          search: this.searchQuery,
          userId: this.userId
        }
      }).then(response => {
        console.log('API响应数据:', response)
        
        if (response && response.posts) {
          this.posts = response.posts.map(post => ({
            ...post,
            likeCount: post.likeCount || 0,
            favoriteCount: post.favoriteCount || 0,
            commentCount: post.commentCount || 0,
            isLiked: !!post.isLiked,
            isFavorited: !!post.isFavorited
          }))
          this.total = response.totalItems || 0
          this.currentPage = (response.currentPage || 0) + 1
        } else {
          this.posts = []
          this.total = 0
          console.error('API返回的数据格式不支持:', response)
          this.$message.error('获取帖子列表失败，服务器返回数据格式错误')
        }
      }).catch(error => {
        console.error('获取帖子列表失败:', error)
        this.$message.error('获取帖子列表失败，请稍后再试')
        this.posts = []
        this.total = 0
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 搜索帖子
    handleSearch() {
      this.currentPage = 1
      this.fetchPosts()
    },
    
    // 分页切换
    handlePageChange(page) {
      this.currentPage = page
      this.fetchPosts()
    },
    handleCreatePost() {
      this.dialogVisible = true
      this.postForm = {
        title: '',
        content: '',
        tags: []
      }
      this.$nextTick(() => {
        this.$refs.postForm && this.$refs.postForm.clearValidate()
      })
    },
    submitPost() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          request({
            url: '/api/community/posts',
            method: 'post',
            data: {
              ...this.postForm,
              userId: this.userId
            }
          }).then(() => {
            this.$message.success('发帖成功')
            this.dialogVisible = false
            this.fetchPosts()
          }).catch(error => {
            console.error('发帖错误:', error);
            if (error.response) {
              console.error('错误状态码:', error.response.status);
              console.error('错误数据:', error.response.data);
            }
            this.$message.error('发帖失败，请稍后再试')
          })
        }
      })
    },
    // 点赞/取消点赞
    async handleLike(postId) {
      try {
        const post = this.posts.find(item => item.id === postId);
        if (!post) {
          console.error(`找不到ID为${postId}的帖子`);
          this.$message.error('操作失败，找不到该帖子');
          return;
        }
        
        const originalIsLiked = post.isLiked;
        const originalLikeCount = post.likeCount;
        
        console.log(`点赞操作前状态 - 帖子ID:${postId}, 已点赞:${originalIsLiked}, 点赞数:${originalLikeCount}`);
        
        const response = await request({
          url: `/api/community/posts/${postId}/like`,
          method: 'post',
          params: {
            userId: this.userId
          }
        });
        
        console.log('点赞响应:', response);
        
        if (response) {
          post.isLiked = response.isLiked;
          post.likeCount = response.likeCount;
          
          console.log(`点赞操作后状态 - 帖子ID:${postId}, 已点赞:${post.isLiked}, 点赞数:${post.likeCount}`);
          this.$message.success(response.isLiked ? '点赞成功' : '已取消点赞');
        }
      } catch (error) {
        console.error('点赞操作失败:', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        const post = this.posts.find(item => item.id === postId);
        if (post) {
          console.log(`恢复原始状态 - 帖子ID:${postId}`);
        }
        this.$message.error('点赞失败，请稍后再试');
      }
    },
    
    // 收藏/取消收藏
    async handleFavorite(postId) {
      try {
        const post = this.posts.find(item => item.id === postId);
        if (!post) {
          console.error(`找不到ID为${postId}的帖子`);
          this.$message.error('操作失败，找不到该帖子');
          return;
        }
        
        const originalIsFavorited = post.isFavorited;
        const originalFavoriteCount = post.favoriteCount;
        
        console.log(`收藏操作前状态 - 帖子ID:${postId}, 已收藏:${originalIsFavorited}, 收藏数:${originalFavoriteCount}`);
        
        const response = await request({
          url: `/api/favorites/toggle/${postId}`,
          method: 'post',
          params: {
            userId: this.userId
          }
        });
        
        console.log('收藏响应:', response);
        
        if (response) {
          post.isFavorited = response.isFavorited;
          post.favoriteCount = response.favoriteCount;
          
          console.log(`收藏操作后状态 - 帖子ID:${postId}, 已收藏:${post.isFavorited}, 收藏数:${post.favoriteCount}`);
          this.$message.success(response.isFavorited ? '收藏成功' : '已取消收藏');
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        const post = this.posts.find(item => item.id === postId);
        if (post) {
          console.log(`恢复原始状态 - 帖子ID:${postId}`);
        }
        this.$message.error('收藏失败，请稍后再试');
      }
    },
    handleComment(postId) {
      this.$router.push(`/community/post/${postId}`)
    },
    handleRemoveTag(tag) {
      this.postForm.tags = this.postForm.tags.filter(t => t !== tag)
    },
    showInput() {
      this.inputTagVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      if (this.inputTagValue && !this.postForm.tags.includes(this.inputTagValue)) {
        this.postForm.tags.push(this.inputTagValue)
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    beforePetImageUpload(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.petImageUrl = e.target.result;
      };
      reader.readAsDataURL(file);
      return false; // 阻止默认上传行为
    },
    submitPetFinder() {
      const formData = new FormData()
      formData.append('description', this.petFinderForm.description)
      formData.append('userId', this.userId)
      
      if (this.petImageUrl) {
        const blob = this.dataURLtoBlob(this.petImageUrl)
        formData.append('image', blob, 'pet-image.jpg')
      }
      
      request({
        url: '/api/community/pet-finder',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log("寻宠响应:", response);
        this.$message.success('提交成功')
        this.showAIPetFinder = false
        this.petFinderForm = {
          description: ''
        }
        this.petImageUrl = ''
      }).catch(error => {
        console.error('寻宠错误:', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.$message.error('提交失败，请稍后再试')
      })
    },
    
    // base64转Blob
    dataURLtoBlob(dataURL) {
      const arr = dataURL.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚';
      }
      // 小于1小时
      if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前';
      }
      // 小于24小时
      if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
      }
      // 小于30天
      if (diff < 30 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
      }
      
      // 大于30天，显示具体日期
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.filter-options {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-options {
  display: flex;
  align-items: center;
}

.post-list {
  min-height: 500px;
}

.loading-container {
  padding: 20px;
}

.empty-tip {
  padding: 50px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.ai-pet-finder-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 999;
}

.post-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.post-item:last-child {
  border-bottom: none;
}

.post-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.post-content {
  margin-bottom: 10px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-actions {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.action-btn {
  margin-right: 15px;
  padding: 0;
}

.active {
  color: #409EFF;
}
</style>
